<template>
  <div>
    {{list}}
    <transition-group name="drag" class="list" tag="ul">
      <li
        @dragenter="dragenter($event, index)"
        @dragover="dragover($event, index)"
        @dragstart="dragstart(index)"
        draggable
        v-for="(item, index) in list"
        :key="item.label"
        class="list-item"
      >{{item.label + "---" + item.id}}</li>
    </transition-group>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        { label: "列表1", id: 1 },
        { label: "列表2", id: 2 },
        { label: "列表3", id: 3 },
        { label: "列表4", id: 4 },
        { label: "列表5", id: 5 },
        { label: "列表6", id: 6 }
      ],
      dragIndex: "",
      enterIndex: ""
    };
  },
  methods: {
    shuffle() {
      this.list = this.$shuffle(this.list);
    },
    // 拖动开始
    dragstart(index) {
      console.log("dragstart");
      this.dragIndex = index;
    },
    // 拖动覆盖
    dragenter(e, index) {
      console.log("enter", e);
      e.preventDefault();
      // 避免源对象触发自身的dragenter事件
      if (this.dragIndex !== index) {
        const moving = this.list[this.dragIndex]; //接收拖动对象
        this.list.splice(this.dragIndex, 1); //删除拖动对象
        this.list.splice(index, 0, moving); //将接收的替换到新的位置
        // // 排序变化后目标对象的索引变成源对象的索引
        this.dragIndex = index;
      }
    },
    // 拖动结束
    dragover(e, index) {
      console.log("over");
      e.preventDefault();
    }
  }
};
</script>
<style lang="less" scoped>
.list {
  list-style: none;
  .drag-move {
    transition: transform 0.3s;
  }
  .list-item {
    cursor: move;
    width: 300px;
    background: #ea6e59;
    border-radius: 4px;
    color: #fff;
    margin-bottom: 6px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
}
</style>